package br.ufrj.ppgi.jemf_advanced_example.plan;

import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import br.ufrj.ppgi.jemf.mobile.FeatureHolder.EnumFeatureType;
import br.ufrj.ppgi.jemf.mobile.bean.Plan;
import br.ufrj.ppgi.jemf.mobile.factory.EmergencyManagementFactory;
import br.ufrj.ppgi.jemf.utils.DateTimeFormat;
import br.ufrj.ppgi.jemf_advanced_example.BuildConfig;
import br.ufrj.ppgi.jemf_advanced_example.CustomActionListener;
import br.ufrj.ppgi.jemf_advanced_example.CustomActionListener.BaseActionListener;
import br.ufrj.ppgi.jemf_advanced_example.R;

/**
 * An activity representing a list of Emergencies.
 * This activity has different presentations for handset and tablet-size devices.
 * On handsets, the activity presents a list of items, which when touched, lead to a {@link PlanDetailActivity} representing item details.
 * On tablets, the activity presents the list of items and item details side-by-side using two vertical panes.
 * <p>
 * The activity makes heavy use of fragments.
 * The list of items is a {@link PlanListFragment} and the item details (if present) is a {@link PlanDetailFragment}.
 * <p>
 * This activity also implements the required {@link PlanListFragment.Callbacks} interface to listen for item selections.
 */
public class PlanListActivity extends Activity implements BaseActionListener {

	/**
	 * Log TAG
	 */
	public static String TAG = "jemf_advanced_example";
	/**
	 * Save Menu Item
	 */
	private static MenuItem savePlanMenu;
    /**
     * Whether or not the activity is in two-pane mode, i.e. running on a tablet device.
     */
    private static boolean isTwoPane;
    // Creation Time.
    private Date creationTime;



	/**
     * Verify if is two pane exhibition (Tablet)
     */
    public static boolean isTwoPane() {
		return isTwoPane;
	}
	public static void setTwoPane(boolean twoPane) {
		isTwoPane = twoPane;
	}



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.plan_activity_item_list);

		// Enabling action bar App icon and behaving it as toggle button.
        getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);
        // Change Title
        setTitle("Plans");
        // Verify if is tablet device
        if (findViewById(R.id.item_detail_container) != null) {
            // The detail container view will be present only in the large-screen layouts (res/values-large and res/values-sw600dp).
        	// If this view is present, then the activity should be in two-pane mode.
            setTwoPane(true);
            // In two-pane mode, list items should be given the 'activated' state when touched.
            ((PlanListFragment) getFragmentManager().findFragmentById(R.id.item_list)).setActivateOnItemClick(true);
        }
        creationTime = new Date(System.currentTimeMillis());
    }



    /**
     * Callback method from {@link CustomActionListener} indicating that the item with the given ID was selected.
     */
	@Override
	public <T> void onItemSelected(T bean) {
		if (BuildConfig.DEBUG) Log.i(TAG, "ListActivity ::: onItemSelected");
        if (isTwoPane()) {
        	// Enable/Disable Save button
        	setEnabledSavePlanMenu(bean != null);
            // In two-pane mode, show the detail view in this activity by adding or replacing the detail fragment using a fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putParcelable(PlanDetailFragment.ARG_ID, (Parcelable) bean);
            PlanDetailFragment detailFragment = new PlanDetailFragment();
            detailFragment.setArguments(arguments);
            getFragmentManager().beginTransaction().replace(R.id.item_detail_container, detailFragment).commit();


        } else {
            // In single-pane mode, simply start the detail activity for the selected item ID.
            Intent detailIntent = new Intent(this, PlanDetailActivity.class);
            detailIntent.putExtra(PlanDetailFragment.ARG_ID, (Parcelable) bean);
            startActivity(detailIntent);
        }
	}
	@SuppressWarnings("unchecked")
	@Override
	public <T> T onItemSave(T bean) {
		if (BuildConfig.DEBUG) Log.i(TAG, "ListActivity ::: onItemSave");
		// When null is to create a new Plan
		if (bean == null) {
			Date now = new Date(System.currentTimeMillis());
			bean = (T) new Plan(DateTimeFormat.DateTimeToString(creationTime), DateTimeFormat.DateTimeToString(now), "NONE", "", "", "", "", "");
		}	
		// JEMF instance
		EmergencyManagementFactory emf = EmergencyManagementFactory.newInstance(this);
		// Save Plan
		bean = emf.getMainFactory(EnumFeatureType.PLAN).getManager().save(bean);
		if (bean != null) {
			Log.i(TAG, bean.toString());
		}
		return bean;
	}
	@Override
	public <T> void onItemRemove(T bean) {
		if (BuildConfig.DEBUG) Log.i(TAG, "ListActivity ::: onItemRemove");
		// JEMF instance
		EmergencyManagementFactory emf = EmergencyManagementFactory.newInstance(this);
		bean = emf.getMainFactory(EnumFeatureType.PLAN).getManager().remove(bean);
        // refresh Detail fragment
        if (isTwoPane()) {
        	//Deselect Plan when passing null
        	this.onItemSelected(null);
        }
	}



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		// Start custom menu
		inflater.inflate(R.menu.menu_list_activity, menu);
		// Hiding menu Info.
		menu.findItem(R.id.action_info).setVisible(false);
		return true;
	}
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
	    super.onPrepareOptionsMenu(menu);
    	savePlanMenu = menu.findItem(R.id.saveItem); 
    	if (isTwoPane()) {
    		// Show button Save when is two pane (tablet)
        	savePlanMenu.setVisible(true);
	    	// Check if the detail fragment is enabled and configure menu accordingly
	    	boolean isDetailEnabled = (findViewById(R.id.item_detail_container).findViewWithTag(PlanDetailFragment.ARG_ID) != null);
	    	setEnabledSavePlanMenu(isDetailEnabled);
    	} else {
        	savePlanMenu.setVisible(false);
        	setEnabledSavePlanMenu(false);
    	}
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case android.R.id.home:
		        finish();
		        return true;
	        case R.id.newItem:
				if (BuildConfig.DEBUG) Log.i(TAG, "ListActivity ::: onOptionsItemSelected ::: NewPlan");
				// Call method to create new Plan
				Plan plan = this.onItemSave(null);
				if (plan != null) {
					this.onItemSelected(plan);
				}
				return true;
	        case R.id.saveItem:
	        	if (isTwoPane()) {
	    			if (BuildConfig.DEBUG) Log.i(TAG, "ListActivity ::: onOptionsItemSelected ::: SavePlan");
	    			// Call method to delete the selected Plan
	    			Plan plan2 = PlanDetailFragment.getPlan();
	    			if (plan2 != null) {
	    				this.onItemSave(plan2);
	    				this.onItemSelected(plan2);
	    			}
	        	}
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }	       
    }
	public static void setEnabledSavePlanMenu(boolean enabled) {
		savePlanMenu.setEnabled(enabled);
	}


	@Override
	public void onUserInteraction() {
		super.onUserInteraction();
		if (BuildConfig.DEBUG) Log.i(TAG, "ListActivity ::: onUserInteraction");
		if (isTwoPane()) {
			// Refresh Plan by input data
			PlanDetailFragment.updateDataFromUI();
		}
	}

}
